﻿using Core;

namespace g_gongjianta.battle.fsm
{
    public class MainFSM<T> : Component, IAwake, IFSM, IFrameUpdate
        where T : AbstractLayer
    {
        private T wholeLayer;

        public EWholeState State { get; private set; }

        public void Awake()
        {
            wholeLayer = Entity.Create<T, IFSM, IFSM>(this, null);

            Switch((int)EWholeState.Idle);
        }

        public void Tick()
        {
            wholeLayer.Update();
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            State = 0;

            wholeLayer.Dispose();
        }


        private int currFrameCnt;
        private int switchCnt;
        private bool CheckSwitch(EWholeState state)
        {
            if (currFrameCnt != UnityEngine.Time.frameCount)
            {
                currFrameCnt = UnityEngine.Time.frameCount;
                switchCnt = 0;
            }
            switchCnt++;

            if (switchCnt > 0)
            {
                if (switchCnt > 20)
                {
                    log.err($"肯定死循环了 state={state} cnt={switchCnt}");
                    return false;
                }
                //log.d("MainFSM", $"循环次数 state={state} cnt={m_switch_cnt}");
            }
            return true;
        }

        public void Switch(int state, int lower_skill = 0)
        {
            var result = CheckSwitch((EWholeState)state);
            if (result == false)
            {
                return;
            }
            State = (EWholeState)state;
            wholeLayer.Switch(state, lower_skill);
        }
    }
}
